﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Syndication;
using System.Text;
using System.Configuration;
using System.Security.Principal;

namespace Microsoft.SqlCommunity.SQLRSS
{
    // This is the implementation of the changes syndication feed singleton WCF service.
    // NOTE: If you change the class name "RSSData" here, you must also update the reference to "RSSData" in Web.config.
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class RSSData : IRSSData
    {
        private FeedMap _FeedMap;

        // When our host invokes this service it must pass us the name of the XML configuration file.
        public RSSData(string feedMapConfigurationFileName)
        {
            _FeedMap = new FeedMap(feedMapConfigurationFileName);
        }

        //Notes for future expansion:
        //The code which might want to sniff arbitrary query parameters would look something like this:
        //MessageProperties properties = OperationContext.Current.IncomingMessageProperties; 
        //HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)properties[HttpRequestMessageProperty.Name]; 
        //string queryString = requestProperty.QueryString;

        /// <summary>
        /// This method is invoked on the server when the web service method is invoked from a client.  Typically the client is an RSS feed store.
        /// Returns the most current changes for the specified connection and table as a syndication feed.  The server and table should be configured for 
        /// Change Tracking.
        /// </summary>
        /// <param name="rssFormat">What format to send the response in (atom or rss)</param>
        /// <param name="connection">The logical name for the connection</param>
        /// <param name="table">The name of the table to get the changes for.</param>
        /// <returns>Either an RSS or Atom feed based on the value of rssFormat</returns>
        public SyndicationFeedFormatter GetDataChanges(string rssFormat, string connection, string table)
        {
            SyndicationFeed feed = _FeedMap.CurrentChanges(connection, table);

            if (rssFormat == "rss")
                return new Rss20FeedFormatter(feed);
            else if (rssFormat == "atom")
                return new Atom10FeedFormatter(feed);
            else return null;

        }
    }
}
